package controller

import (
	"net/http"
	"strconv"

	"gitee.com/wangshh_123/cross-pay-go/src/models"
	"gitee.com/wangshh_123/cross-pay-go/src/service"
	"gitee.com/wangshh_123/cross-pay-go/src/utils/common"

	"github.com/gin-gonic/gin"
)

// DepartmentController 部门控制器
type DepartmentController struct {
	departmentService *service.DepartmentService
}

// NewDepartmentController 创建部门控制器实例
func NewDepartmentController() *DepartmentController {
	return &DepartmentController{
		departmentService: service.NewDepartmentService(),
	}
}

// CreateDepartment 创建部门
// @Summary 创建部门
// @Description 创建新的部门
// @Tags departments
// @Accept json
// @Produce json
// @Param department body models.DepartmentCreateRequest true "部门信息"
// @Success 200 {object} map[string]interface{} "成功响应"
// @Failure 400 {object} map[string]interface{} "请求错误"
// @Failure 500 {object} map[string]interface{} "服务器错误"
// @Router /api/admin/departments [post]
func (c *DepartmentController) CreateDepartment(ctx *gin.Context) {
	var req models.DepartmentCreateRequest
	if err := ctx.ShouldBindJSON(&req); err != nil {
		common.Error(ctx, http.StatusBadRequest, "INVALID_PARAMS", err)
		return
	}

	// 获取当前用户ID
	userID, exists := ctx.Get("user_id")
	if !exists {
		common.Error(ctx, http.StatusUnauthorized, "unauthorized", nil)
		return
	}

	department, err := c.departmentService.CreateDepartment(ctx, &req, userID.(int64))
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, err.Error(), err)
		return
	}

	common.Success(ctx, "部门创建成功", department)
}

// UpdateDepartment 更新部门
// @Summary 更新部门
// @Description 更新部门信息
// @Tags departments
// @Accept json
// @Produce json
// @Param id path int true "部门ID"
// @Param department body models.DepartmentUpdateRequest true "部门信息"
// @Success 200 {object} map[string]interface{} "成功响应"
// @Failure 400 {object} map[string]interface{} "请求错误"
// @Failure 500 {object} map[string]interface{} "服务器错误"
// @Router /api/admin/departments/{id} [put]
func (c *DepartmentController) UpdateDepartment(ctx *gin.Context) {
	idStr := ctx.Param("id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		common.Error(ctx, http.StatusBadRequest, "INVALID_DEPARTMENT_ID", err)
		return
	}

	var req models.DepartmentUpdateRequest
	if err := ctx.ShouldBindJSON(&req); err != nil {
		common.Error(ctx, http.StatusBadRequest, "INVALID_PARAMS", err)
		return
	}

	// 获取当前用户ID
	userID, exists := ctx.Get("user_id")
	if !exists {
		common.Error(ctx, http.StatusUnauthorized, "unauthorized", nil)
		return
	}

	department, err := c.departmentService.UpdateDepartment(ctx, id, &req, userID.(int64))
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, err.Error(), err)
		return
	}

	common.Success(ctx, "部门更新成功", department)
}

// DeleteDepartment 删除部门
// @Summary 删除部门
// @Description 删除部门（软删除）
// @Tags departments
// @Accept json
// @Produce json
// @Param id path int true "部门ID"
// @Success 200 {object} map[string]interface{} "成功响应"
// @Failure 400 {object} map[string]interface{} "请求错误"
// @Failure 500 {object} map[string]interface{} "服务器错误"
// @Router /api/admin/departments/{id} [delete]
func (c *DepartmentController) DeleteDepartment(ctx *gin.Context) {
	idStr := ctx.Param("id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		common.Error(ctx, http.StatusBadRequest, "INVALID_DEPARTMENT_ID", err)
		return
	}

	// 获取当前用户ID
	userID, exists := ctx.Get("user_id")
	if !exists {
		common.Error(ctx, http.StatusUnauthorized, "unauthorized", nil)
		return
	}

	err = c.departmentService.DeleteDepartment(ctx, id, userID.(int64))
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, err.Error(), err)
		return
	}

	common.Success(ctx, "部门删除成功", nil)
}

// GetDepartmentList 获取部门列表
// @Summary 获取部门列表
// @Description 分页获取部门列表
// @Tags departments
// @Accept json
// @Produce json
// @Param page query int true "页码"
// @Param page_size query int true "每页数量"
// @Param name query string false "部门名称"
// @Param code query string false "部门编码"
// @Param status query string false "状态"
// @Success 200 {object} map[string]interface{} "成功响应"
// @Failure 400 {object} map[string]interface{} "请求错误"
// @Failure 500 {object} map[string]interface{} "服务器错误"
// @Router /api/admin/departments [get]
func (c *DepartmentController) GetDepartmentList(ctx *gin.Context) {
	var req models.DepartmentListRequest
	if err := ctx.ShouldBindQuery(&req); err != nil {
		common.Error(ctx, http.StatusBadRequest, "INVALID_QUERY_PARAMS", err)
		return
	}

	result, err := c.departmentService.GetDepartmentList(ctx, &req)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, err.Error(), err)
		return
	}

	common.Success(ctx, result)
}

// CreateDepartmentUser 创建部门用户关联
// @Summary 创建部门用户关联
// @Description 将用户分配到部门
// @Tags department-users
// @Accept json
// @Produce json
// @Param department_user body models.DepartmentUserCreateRequest true "部门用户关联信息"
// @Success 200 {object} map[string]interface{} "成功响应"
// @Failure 400 {object} map[string]interface{} "请求错误"
// @Failure 500 {object} map[string]interface{} "服务器错误"
// @Router /api/admin/department-users [post]
func (c *DepartmentController) CreateDepartmentUser(ctx *gin.Context) {
	var req models.DepartmentUserCreateRequest
	if err := ctx.ShouldBindJSON(&req); err != nil {
		common.Error(ctx, http.StatusBadRequest, "INVALID_PARAMS", err)
		return
	}

	// 获取当前用户ID
	userID, exists := ctx.Get("user_id")
	if !exists {
		common.Error(ctx, http.StatusUnauthorized, "unauthorized", nil)
		return
	}

	departmentUser, err := c.departmentService.CreateDepartmentUser(ctx, &req, userID.(int64))
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, err.Error(), err)
		return
	}

	common.Success(ctx, "用户分配部门成功", departmentUser)
}

// UpdateDepartmentUser 更新部门用户关联
// @Summary 更新部门用户关联
// @Description 更新用户在部门中的信息
// @Tags department-users
// @Accept json
// @Produce json
// @Param id path int true "部门用户关联ID"
// @Param department_user body models.DepartmentUserUpdateRequest true "部门用户关联信息"
// @Success 200 {object} map[string]interface{} "成功响应"
// @Failure 400 {object} map[string]interface{} "请求错误"
// @Failure 500 {object} map[string]interface{} "服务器错误"
// @Router /api/admin/department-users/{id} [put]
func (c *DepartmentController) UpdateDepartmentUser(ctx *gin.Context) {
	idStr := ctx.Param("id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		common.Error(ctx, http.StatusBadRequest, "INVALID_DEPARTMENT_USER_ID", err)
		return
	}

	var req models.DepartmentUserUpdateRequest
	if err := ctx.ShouldBindJSON(&req); err != nil {
		common.Error(ctx, http.StatusBadRequest, "INVALID_PARAMS", err)
		return
	}

	// 获取当前用户ID
	userID, exists := ctx.Get("user_id")
	if !exists {
		common.Error(ctx, http.StatusUnauthorized, "unauthorized", nil)
		return
	}

	departmentUser, err := c.departmentService.UpdateDepartmentUser(ctx, id, &req, userID.(int64))
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, err.Error(), err)
		return
	}

	common.Success(ctx, "部门用户关联更新成功", departmentUser)
}

// DeleteDepartmentUser 删除部门用户关联
// @Summary 删除部门用户关联
// @Description 将用户从所有部门中移除（设置所有active状态为inactive）
// @Tags department-users
// @Accept json
// @Produce json
// @Param user_id path int true "用户ID"
// @Success 200 {object} map[string]interface{} "成功响应"
// @Failure 400 {object} map[string]interface{} "请求错误"
// @Failure 500 {object} map[string]interface{} "服务器错误"
// @Router /api/admin/department-users/{user_id} [delete]
func (c *DepartmentController) DeleteDepartmentUser(ctx *gin.Context) {
	userIDStr := ctx.Param("id") // 这里的id实际上是user_id
	userID, err := strconv.ParseInt(userIDStr, 10, 64)
	if err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_user_id", err)
		return
	}

	// 获取当前操作用户ID
	operatorID, exists := ctx.Get("user_id")
	if !exists {
		common.Error(ctx, http.StatusUnauthorized, "unauthorized", nil)
		return
	}

	err = c.departmentService.DeleteDepartmentUser(ctx, userID, operatorID.(int64))
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, err.Error(), err)
		return
	}

	common.Success(ctx, "用户从所有部门移除成功", nil)
}

// GetDepartmentUserList 获取部门用户列表
// @Summary 获取部门用户列表
// @Description 分页获取部门用户关联列表
// @Tags department-users
// @Accept json
// @Produce json
// @Param page query int true "页码"
// @Param page_size query int true "每页数量"
// @Param department_id query int false "部门ID"
// @Param user_id query int false "用户ID"
// @Param status query string false "状态"
// @Success 200 {object} map[string]interface{} "成功响应"
// @Failure 400 {object} map[string]interface{} "请求错误"
// @Failure 500 {object} map[string]interface{} "服务器错误"
// @Router /api/admin/department-users [get]
func (c *DepartmentController) GetDepartmentUserList(ctx *gin.Context) {
	var req models.DepartmentUserListRequest
	if err := ctx.ShouldBindQuery(&req); err != nil {
		common.Error(ctx, http.StatusBadRequest, "INVALID_QUERY_PARAMS", err)
		return
	}

	result, err := c.departmentService.GetDepartmentUserList(ctx, &req)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, err.Error(), err)
		return
	}

	common.Success(ctx, result)
}

// GetUserDepartmentHistory 获取用户部门历史
// @Summary 获取用户部门历史
// @Description 获取指定用户的所有部门历史记录（包括当前和已离开的部门）
// @Tags department-users
// @Accept json
// @Produce json
// @Param user_id path int true "用户ID"
// @Param page query int false "页码，默认1"
// @Param page_size query int false "每页数量，默认10"
// @Success 200 {object} map[string]interface{} "成功响应"
// @Failure 400 {object} map[string]interface{} "请求错误"
// @Failure 500 {object} map[string]interface{} "服务器错误"
// @Router /api/admin/users/{user_id}/department-history [get]
func (c *DepartmentController) GetUserDepartmentHistory(ctx *gin.Context) {
	userIDStr := ctx.Param("user_id")
	userID, err := strconv.ParseInt(userIDStr, 10, 64)
	if err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_user_id", err)
		return
	}

	// 获取分页参数
	page, _ := strconv.Atoi(ctx.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(ctx.DefaultQuery("page_size", "10"))

	// 调用服务层方法获取用户部门历史
	departmentUsers, total, err := c.departmentService.GetUserDepartmentHistory(ctx, userID, page, pageSize)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, err.Error(), err)
		return
	}

	// 返回分页结果
	common.Success(ctx, gin.H{
		"department_users": departmentUsers,
		"total":            total,
		"page":             page,
		"page_size":        pageSize,
		"total_pages":      (total + int64(pageSize) - 1) / int64(pageSize),
	})
}

// TransferDepartmentUser 用户更换部门
func (c *DepartmentController) TransferDepartmentUser(ctx *gin.Context) {
	var req models.DepartmentUserTransferRequest
	if err := ctx.ShouldBindJSON(&req); err != nil {
		common.Error(ctx, http.StatusBadRequest, "INVALID_PARAMS", err)
		return
	}

	userID, exists := ctx.Get("user_id")
	if !exists {
		common.Error(ctx, http.StatusUnauthorized, "unauthorized", nil)
		return
	}

	err := c.departmentService.TransferDepartmentUser(ctx, &req, userID.(int64))
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, err.Error(), err)
		return
	}

	common.Success(ctx, "用户部门更换成功", nil)
}
